package main

import (
	"log"
	"yundian/internel/app/models/placemodel/places"
	"yundian/internel/pkg/dbs"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
)

func main()  {
	dingo.InitViper("./configs/adm.yaml")
	dbs.NewMysqlComponent().Step()

	ids := getAllAgentUser().Unwrap().([]int)
	for id := range ids {
		totalUsers := getallTeams(id)
		totalPlaces := countAllPlacesByUserIds(totalUsers).Unwrap().([]int) // 所有门店ID
		if ok := updatePlacesIsBusinessField(totalPlaces).Unwrap().(bool); ok {
			log.Println("修改成功")
		}
	}
}

// 获取所有代理商
func getAllAgentUser() *dingo.ErrorWrap {
	var userIds []int
	sql := "SELECT id FROM users WHERE is_admin = 8 and parent_id = 2 and id != 403746"
	db := global.Orm.Raw(sql).Find(&userIds)
	return dingo.ErrorIf(db.Error, userIds)
}

// 获取所有用户
func getallTeams(id int) []int {
	isLoop := true
	var userIds, ids []int
	ids = append(ids, id)
	for isLoop {
		tempUserIds := countAllUsersByParentId(ids).Unwrap().([]int)
		if len(tempUserIds) == 0 {
			isLoop = false
		} else {
			userIds = append(userIds, tempUserIds...)
			ids = tempUserIds
		}
	}
	return userIds
}

// 所有下级用户ID
func countAllUsersByParentId(ids []int) *dingo.ErrorWrap {
	var total []int
	db := global.Orm.Table("users").
		Select("id").
		Where("parent_id in (?)", ids).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 所有下级门店ID
func countAllPlacesByUserIds(ids []int) *dingo.ErrorWrap {
	var total []int
	db := global.Orm.Table("places").
		Select("id").
		Where("user_id in (?)", ids).
		Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 修改运营状态
func updatePlacesIsBusinessField(ids []int) *dingo.ErrorWrap {
	m := &placemodel.PlaceModel{}
	m.IsBusiness = 1
	db := global.Orm.Debug().Table("places").
		Select("is_business").
		Where("id in (?)", ids).
		Where("is_business = 2").
		Model(&m).Updates(m)
	return dingo.ErrorIf(db.Error, true)
}